package com.game2048

import android.os.Bundle
import android.widget.Toast

import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp

import com.game2048.Game.Status
import com.game2048.ui.theme.Game2048Theme

// 主活动
class MainActivity: ComponentActivity() {
    private lateinit var mGame: Game    // 游戏

    /**
     * 界面布局。
     */
    @Composable
    fun Greeting() {
        // 计算所有水平方向或垂直方向的线宽度尺寸之和（边框+所有内部的线）
        val allLineWidth = Const.GAME_BOARD_PEN_WIDTH * (Const.GAME_BOARD_GRID_COUNT_H + 1)

        // 计算格的尺寸
        Const.GRID_SIZE = (resources.displayMetrics.widthPixels -
            Const.GAME_BOARD_PADDING * resources.displayMetrics.density * 2) / Const.GAME_BOARD_GRID_COUNT_H - allLineWidth

        // 计算游戏区域的尺寸
        val gameBoardSizePx = Const.GRID_SIZE * Const.GAME_BOARD_GRID_COUNT_H + allLineWidth

        // 布局
        Column(Modifier.fillMaxSize(), Arrangement.Center, Alignment.CenterHorizontally) {
            // 游戏区域
            mGame.GameBoard(gameBoardSizePx)

            // 按钮
            Button(
                onClick = mGame.start,
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(Const.GAME_BOARD_PADDING.dp)
            ) {
                val textResId = if (mGame.status == Status.PLAYING) R.string.IDS_RESTART else R.string.IDS_START
                Text(this@MainActivity.getString(textResId))
            }

            // 吐司窗口
            if (mGame.status == Status.WON) {
                Toast.makeText(this@MainActivity, super.getString(R.string.IDS_WON), Toast.LENGTH_LONG).show()
            } else if (mGame.status == Status.LOST) {
                Toast.makeText(this@MainActivity, super.getString(R.string.IDS_LOST), Toast.LENGTH_LONG).show()
            }
        }
    }

    /**
     * 创建事件的响应方法。
     * @param savedInstanceState    保存的实例状态
     */
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        this.enableEdgeToEdge()

        // 初始化成员
        mGame = Game()

        // 设置内容
        this.setContent {
            Game2048Theme {
                this.Greeting()
            }
        }
    }
}
